<template>
  <div class="search-container" >
    <!-- search 事件在手机键盘上的完成或者搜索 -->
    <!-- cancel 事件在点击取消文字的时候触发 -->
    <!-- 在 van-search 外层增加 form 标签，且 action 不为空，即可在 iOS 输入法中显示搜索按钮。 -->
    <form action="/"  class="search-box">
      <van-search
        v-model="searchText"
        show-action
        shape="round"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @clear="resultShow=false"
        background="#3296fa"
      />
    </form>
    
    <!-- 搜索结果 -->
    <search-result  
     :search-text="searchText"
      
      v-if="resultShow" />
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <search-suggestion
     :search-text="searchText" 
     v-else-if="searchText" 
     @search="onSearch"
     />
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <search-history
      :search-history="searchHistories"
      @search="onSearch"
      v-else />
    <!-- /搜索历史记录 -->
  </div>
</template>
<script>
import SearchResult from './components/search-result'
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import { setItem,getItem } from '@/utils/storage'
export default {
  name:'Search',
  components: {
    SearchResult,
    SearchHistory,
    SearchSuggestion
  },
  data() {
    return {
      searchText: '', // 输入文字
      resultShow:false, // 搜索结果是否显示
      searchHistories:getItem('TOUTIAO_HISTORY') || []  // 搜索历史
    }
  },
  watch:{
    searchHistories:{
      deep:true,
      handler(){
        setItem('TOUTIAO_HISTORY',this.searchHistories)
      }
    }
  },
  methods: {
    onSearch(val) {
      // 去重
      let idx = this.searchHistories.findIndex(item=>item===val)
      if(idx !== -1) this.searchHistories.splice(idx,1)
      // 放入
      this.searchHistories.unshift(val)
      this.searchText = val
      this.resultShow = true
    },
    onCancel(){
      this.$router.back()
    }
  },
}
</script>
<style lang="less" scoped>
 .van-search__action{
  color: #fff;
}
.search-box{
  position: sticky;
  top: 0;
  z-index: 1000;
}
</style>